package chaoyue.study.handler;

import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 自定义异常处理器
 * 处理断言匹配失败时的返回内容
 */
@Component
@Order(-1) // 提高加载的优先级
public class MyErrorHandler extends AbstractErrorWebExceptionHandler {

    public MyErrorHandler(ErrorAttributes errorAttributes,
                          ApplicationContext applicationContext,
                          ServerCodecConfigurer serverCodecConfigurer) {
        super(errorAttributes, new WebProperties.Resources(), applicationContext);
        super.setMessageReaders(serverCodecConfigurer.getReaders());
        super.setMessageWriters(serverCodecConfigurer.getWriters());
    }

    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        // 获取异常信息
        Map<String, Object> errorMap = getErrorAttributes(request, ErrorAttributeOptions.defaults());
        // 添加自定义的消息内容
        errorMap.put("myMessage","出错啦！");
        // 构建响应
        return ServerResponse.status(HttpStatus.NOT_FOUND) // 指定响应码
                .contentType(MediaType.APPLICATION_JSON) // 指定响应媒体类型
                .body(BodyInserters.fromValue(errorMap));// 指定响应内容（这边将异常信息作为响应内容进行封装）
    }
}
